package com.test3;

import java.util.HashSet;
import java.util.Iterator;

/**
 * HashSet集合的使用
 * 存储机构：哈希表
 */
public class HashSetTest {
    public static void main(String[] args) {
        HashSet<String> hashSet = new HashSet<>();
        //添加元素
        hashSet.add("王林");
        hashSet.add("苏铭");
        hashSet.add("孟浩");
        hashSet.add("白小纯");
//        hashSet.add("王林");//重复的会添加失败
        System.out.println(hashSet);//[孟浩, 王林, 白小纯, 苏铭]
        //删除
        hashSet.remove("孟浩");
        System.out.println(hashSet);//[王林, 白小纯, 苏铭]
        //遍历
        //foreach
        hashSet.forEach(e -> System.out.println(e));
        //迭代器
        Iterator<String> it = hashSet.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }
        //判断
        System.out.println(hashSet.contains("苏铭"));//true
        System.out.println(hashSet.isEmpty());//false

        HashSet<Students> hashSet1 = new HashSet<>();
        Students s1 = new Students("刘德华",20);
        Students s2 = new Students("黎明",22);
        Students s3 = new Students("张学友",18);
        hashSet1.add(s1);
        hashSet1.add(s2);
        hashSet1.add(s3);
        hashSet1.add(s1);
        System.out.println(hashSet1.size());//3
        hashSet1.remove(new Students("张学友",18));
        System.out.println(hashSet1.size());//2,因为重写过equals
        //遍历，判断和上面一样
    }
}
